package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.mapper.StrategyMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    //关联mapper
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    //关联mapper
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //获取文章对象,此时里面有新鲜的文章内容了,缺个文章id
        StrategyContent strategyContent = strategyDetail.getStrategyContent();

        Date date = new Date();
        //如果状态为发布要设置发布时间
        if(strategyDetail.getState()){
            strategyDetail.setReleaseTime(date);
        }
        //没填序列时自动设置序列
        if(strategyDetail.getSequence()==null){
            //去数据库查询当前分类下已经有多少数据
            int max=strategyDetailMapper.selectMaxSequence(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(max+1);
        }
        //id为空,新增操作
        if(strategyDetail.getId()==null){
            //新增操作要设置创建时间
            strategyDetail.setCreateTime(date);
            strategyDetailMapper.insert(strategyDetail);
            //主键关联,将刚刚生成的主键存入对象
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.insert(strategyContent);
        }else{
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //主键关联
            strategyContent.setId(strategyDetail.getId());
            strategyContentMapper.updateByPrimaryKey(strategyContent);
        }
    }

    @Override
    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<StrategyDetail>(list);
    }

    @Override
    public StrategyContent getContentById(Long detailId) {
        return strategyContentMapper.selectByPrimaryKey(detailId);
    }

    @Override
    public StrategyDetail getById(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }


}
